home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 561 < prev    next >
Internet Message Format  |  1996-08-06  |  2KB

  1. Path: solon.com!not-for-mail
  2. From: tada@athena.mit.edu (Michael J Zehr)
  3. Newsgroups: comp.lang.c.moderated,comp.std.c
  4. Subject: 'h' modifier in printf
  5. Date: 13 Mar 1996 20:24:44 -0600
  6. Organization: Massachusetts Institute of Technology
  7. Sender: clc@solutions.solon.com
  8. Approved: clc@solutions.solon.com
  9. Message-ID: <4i801c$455@solutions.solon.com>
  10. NNTP-Posting-Host: solutions.solon.com
  11.  
  12.  
  13. I was recently asked a question about printf whose answer I couldn't
  14. determine by reading K&R2 (and alas the company doesn't have a copy of
  15. the standard to refer to).
  16.  
  17. The "h" modifier says the corresponding argument will be printed as a
  18. short or unsigned short.
  19.  
  20. So, given:
  21.  
  22. short s;
  23. printf("%d", s);
  24. printf("%hd", s);
  25.  
  26. (Assuming of course that s has been initialized at some point.)
  27.  
  28. Can these two ever be different?  I'm aware of course that the short is
  29. widened to an int during the function call, but this preserves the
  30. value.
  31.  
  32. (A totally non-relevant piece of information is that on at least one
  33. platform there is never a difference between these two for any value of
  34. s from SHRT_MIN to SHRT_MAX.  But that doesn't answer the question.)
  35.  
  36. This is the main question I'm interested, but as a followup, if these
  37. always result in the same output, why is the 'h' modifier defined in the
  38. first place?
  39.  
  40. Some speculations:
  41.  
  42. int i;
  43. printf("%hd", i);
  44. printf("%d", (short)i);
  45.  
  46. This question is stretching a bit to try to find what if anything the
  47. 'h' modifier is ever used for.  Certainly the first line would have a
  48. different result without the 'h', but casting seems like it ought to
  49. have the same result.
  50.  
  51.  
  52. K&R2 is silent on whether "%hn" is valid as a conversion specifier.  If
  53. so, clearly this is a case in which the 'h' is absolutely required to
  54. get the desired behavior.
  55.  
  56. Thanks,
  57. michael j zehr
  58.